﻿using System;
using Caliburn.Micro;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using ThunderboltInterfaceSharp.ViewModels.UserControls;
using ThunderboltIocFrame.Interface;
using ThunderboltIocFrame;
using ThunderboltInterfaceSharp.ViewModels.UserControls.Download;

namespace ThunderboltInterfaceSharp.ViewModels;

public class ThunderStartViewModel : Screen
{
	ThunderStartBackgroundWorker _startWorker;
	ThunderMainViewModel _mainViewModel;
	FloatingViewModel _floatingViewModel;
	public IContainer MyContainer;
	public double LoadProgress { get; set; }
	public ThunderStartViewModel()
	{
		InitContainer();
		InitWorker();
	}

	public void InitWorker()
	{
		_startWorker = MyContainer.Get<ThunderStartBackgroundWorker>(nameof(ThunderStartBackgroundWorker));
		_startWorker.Start();
		_startWorker.WorkProcessEvent += () =>
		{
			//_mainViewModel = new ThunderMainViewModel();
			_mainViewModel = MyContainer.Get<ThunderMainViewModel>(nameof(ThunderMainViewModel));
			_floatingViewModel = new FloatingViewModel();
		};
		_startWorker.WorkCompletedEvent += RenderMainView;
		_startWorker.ProcessChangedEvent += ProgressAdvance;
	}
	private void RenderMainView()
	{
		var windowManager = IoC.Get<IWindowManager>();
		windowManager.ShowWindowAsync(_mainViewModel);
		windowManager.ShowWindowAsync(_floatingViewModel);
		this.TryCloseAsync();
	}
	private void ProgressAdvance(int iPercentage)
	{
		LoadProgress =  (double)iPercentage/100.00;
	}
	private void InitContainer()
	{
		var builder = ContainerBuilder.GetBuilder();
		builder.RegisterSingleton<TopLevelSidebarViewModel>();
		builder.RegisterSingleton<DownloadViewModel>();
		builder.RegisterSingleton<DownloadSidebarViewModel>();
		builder.RegisterSingleton<ThunderMainViewModel>();
		builder.RegisterSingleton<ThunderStartBackgroundWorker>();
		MyContainer = builder.Build();
	}
}